<?php

namespace MyBlog\Libs;

use Qiniu\Auth;
use Qiniu\Storage\UploadManager;
use Qiniu\Processing\ImageUrlBuilder;

class QiniuUtils {
	
	private $auth;
	private $token;
	public static $PREFIX = 'uploads/public/';
	public static $WATERTEXT = 'www.stusay.com';
	
	public function __construct() {
		$this->auth = new Auth(config('filesystems.disks.qiniu.access_key'), config('filesystems.disks.qiniu.secret_key'));
		$this->token = $this->auth->uploadToken(config('filesystems.disks.qiniu.bucket'));
	}
	
	public static function filenameEx($file) {
		$oName = $file->getClientOriginalName();
		$oExt = $file->getClientOriginalExtension();
		$nName = md5($oName . time() . rand()) . '.' . $oExt;
		$filePath = $file->getRealPath();
		return ['key' => $nName, 'filePath' => $filePath];
	}
	
	public static function upload($file) {
		$upManager = new UploadManager();
		$qiniu = new QiniuUtils();
		$fileInfo = $qiniu->filenameEx($file);
		list($ret, $err) = $upManager->putFile($qiniu->token, $qiniu::$PREFIX.'images/'.$fileInfo['key'], $fileInfo['filePath']);
		if ($err !== null) {
		    return false;
		} else {
		    return $ret['key'];
		}
	}
	
	public static function getUrl($imgPath, $dimension = null) {
		$imgBuilder = new ImageUrlBuilder();
		$qiniu = new QiniuUtils();
		$url = config('filesystems.disks.qiniu.custom_url').$imgPath;
		if(is_null($dimension)) {
			$imgUrl = $imgBuilder->waterText($url, $qiniu::$WATERTEXT, '楷体', 600, 'gray');
		}else {
			$dimenArr = explode('x', $dimension);
			$thumbnail = $imgBuilder->thumbnail($url, 1, $dimenArr[0], $dimenArr[1]);
			$imgUrl = $imgBuilder->waterText($thumbnail, $qiniu::$WATERTEXT, '楷体', 300, 'gray');
		}
		return $imgUrl;
	}
	
	public static function deleteObject($ossKey) {
		
	}
}
